<?php
/*
+ --------------------------------------------------- +
|  Ineo Article Manager - Version 1.x
|  Copyright © 2005-2008, Dan Cryer and William McGann
+ --------------------------------------------------- +

Ineo Article Manager is free software; you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as published by
the Free Software Foundation.

Ineo Article Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ineo; see the file License.txt.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

*/

/**
* Ineo - Modules - Articles
*  
* This module handles all front-end actions related to articles.
*
* @package		Ineo
* @subpackage   Modules
* @author		Dan Cryer & William McGann
* @copyright	Dan Cryer & William McGann
* @version		1.0.0
*/
class ineo_mod_article
{
  var $ipsclass;
  var $core;
  
  /**
  * Load article libraries
  */
  function module_init()
  {
      $this->lib_global =& $this->core->load_library('global');
      $this->lib_art    =& $this->core->load_library('articles');
      
      $this->core->load_template('articles');
  }
  
  function view()
  {
    /**
    * This one speaks for itself. Pulls article information and puts it on a page for your viewin' pleasure.
    */
    $artid = intval( $this->ipsclass->input['id'] );
    $article = $this->lib_art->load_article_data( $artid );
    
    // If it's a queued article and the member isn't a mod, error 'em out.
    if ( $article['article_is_queued'] == '1' && $this->ipsclass->member['g_ams_ismod'] == '0' )
    {
      $this->core->error( 'ams_artview_queued' );
      return;
    }
    
    // If article doesn't exist, this prevents a nasty SQL error.
    if ( !$article )
    {
      $this->core->error( 'ams_artiview_noart' );
      return;
    }
    
	  $this->core->title .= ' - ' . $article['article_title'];

	  $this->core->nav_add( $article['category_name'], 'showcat=' . $article['article_cat_id'] );  
    $this->core->nav_add( $article['article_title'], 'showarticle=' . $article['article_id'] );
    
    // Creating dates from timestamps. ips_kernel > all
    $dates = array( 'created_date' => $this->ipsclass->get_date( $article['article_created_date'], '' ),
                    'edited_date' => $this->ipsclass->get_date( $article['article_edited_date'], '' ) );

    // Hand the article's content to the application for parsing
    $body = $this->core->api->display_parse( $article['content_content'] );
    
    // Determine what the article views value should be set to, then do eet on shutdown.
    $article['article_views'] = $article['article_views'] + 1;
    $this->ipsclass->DB->do_update( 'ams_articles', array( 'article_views' => $article['article_views'] ), 'article_id = ' . $this->ipsclass->input['id'], true );
    
    // Build resources box
    $this->ipsclass->DB->simple_construct( array( 'select' => '*',
	                                              'from' => 'ams_attachments',
	                                              'where' => 'attach_article = '.intval($this->ipsclass->input['id']) ) );
    $this->ipsclass->DB->simple_exec();
    $attachments = '';
    while( $data = $this->ipsclass->DB->fetch_row() )
    {
      $attachments .= '- <a href="'.$this->core->base_url.'downloadfile='.$data['attach_id'].'">
                      '.$data['attach_file'].'</a> <i>'.$this->ipsclass->size_format($data['attach_size']).'</i><br />';
    }
    if ( $article['article_links'] != '' )
    {
      $resource_links = '';
      $link_array = explode( "\n", str_replace( "<br />", "\n", $article['article_links']) );
      foreach ( $link_array as $link )
      {
        $ldata = explode( '||', $link);
        if ( !$ldata['1'] ) { $desc = ''; }
        else { $desc = ' <i>'.$ldata['1'].'</i>'; }
        $resource_links .= '- <a href="'.$ldata['0'].'" target="_blank">'.$ldata['0'].'</a> '.$desc.'<br />';
      }
    }
    $resources = $this->core->templates['articles']->art_resources($attachments,$resource_links);

    $topic_link = $this->topic_manager( $article );
    $this->core->out .= $this->core->templates['articles']->article_index($article,$dates,$body,$topic_link,$resources);
    
    //----
    // Menu Additions:
    //----
    
    // Create the block:
    $this->core->menu_block( 'ams_this_article' );
    
    // Set up the links:
    $opts = array( 
    	'ams_article_revisions' => 'mod=moderator&op=rev_list&id='.$this->ipsclass->input['id'],
    	'ams_article_watch'     => 'mod=global&op=watch_add_art&id=' . $this->ipsclass->input['id'],
    			);
    
    // Add 'article options' section:
    $this->core->menu_block_section( 'ams_article_options' , $opts );
    
    if ( $this->ipsclass->vars['ams_rating'] == 1 )
    {
      // Pull voter information.
      $this->ipsclass->DB->simple_construct( array( 'select' => 'sum( rate_rating ) as rating_total, count( rate_rating ) as rating_count',
                                                    'from' => 'ams_rating',
                                                    'where' => 'rate_artid = '.$article['article_id'] ) );
      $this->ipsclass->DB->simple_exec();
      $rate_data = $this->ipsclass->DB->fetch_row();
    
      $this->ipsclass->DB->simple_construct( array( 'select' => '*', 'from' => 'ams_rating', 'where' => 'rate_artid = '.$article['article_id'].' AND rate_mid = '.$this->ipsclass->member['id'] ));
      $this->ipsclass->DB->simple_exec();
      $mrate_data = $this->ipsclass->DB->fetch_row();
    
      $rating = ( $rate_data['rating_count'] == 0 ) ? 'unrated' : $rate_data['rating_total'] / $rate_data['rating_count'] ;
    	$rating = round($rating,0);
      $rate_box = $this->core->templates['articles']->rating_box($mrate_data,$rate_data,$rating);
    
      // Add 'article rating' section:
      $this->core->menu_block_section( 'ams_article_rating', $rate_box);
    }
    
    // Set created by info:
    /**
    * @todo We needs to fix this... IPB-only linkage going on.
    */
    if ( $article['article_author'] == 0 )
    {
      $sec = "<b>" . $this->ipsclass->lang['ams_created_by'] . ":</b> <i>" . $article['members_display_name'] ."</i>
      <br /><b>{$this->ipsclass->lang['ams_on']}:</b> " . $dates['created_date'];
    }
    else
    {
      $sec = "<b>" . $this->ipsclass->lang['ams_created_by'] . ":</b> " .
    	    "<a href='{$this->ipsclass->base_url}showuser={$article['article_author']}'>" .
    		  $article['members_display_name'] .
    		  "</a>
    		  <br />
    		  <b>{$this->ipsclass->lang['ams_on']}:</b> " . $dates['created_date'];
    }
    
    // Set edited by info:
    if( !empty( $article['last_edited_by'] ) )
    {
      /**
      * @todo We needs to fix this... IPB-only linkage going on.
      */
      if ( $article['article_edited_by'] == 0 )
      {
   	 	  $sec .= "<br /><br /><b>" . $this->ipsclass->lang['ams_last_edited_by'] . ":</b> <i>" . $article['last_edited_by'] . "</i>" .
    	  "<br /><b>{$this->ipsclass->lang['ams_on']}:</b> {$dates['edited_date']}";
      }
      else
      {
   	 	  $sec .= "<br /><br /><b>" . $this->ipsclass->lang['ams_last_edited_by'] . ":</b> " .
    	  "<a href='{$this->ipsclass->base_url}showuser={$article['article_edited_by']}'>" .
    	  $article['last_edited_by'] . "</a>" .
    	  "<br /><b>{$this->ipsclass->lang['ams_on']}:</b> {$dates['edited_date']}";
      }
    }
    
    // Set view info:
    $sec .= "<br /><br /><b>{$this->ipsclass->lang['ams_views']}:</b> {$article['article_views']}";
    
    // Add article info section:
    $this->core->menu_block_section( 'ams_article_info' , $sec );
    
    // Add it to the menu:
    $this->core->menu_add_block();
    
    // Append the article title to the page title
    $this->ipsclass->vars['ams_page_title'] .= ' -> '.$article['article_title'];
  }
  
  /**
  * This function makes a purdy preview of the article, duhr.
  */
  function preview()
  {
	$this->lib_global =& $this->core->load_library('global');
	$this->lib_global->ajax_utf8_safe();
    $text = $this->core->api->database_parse_only( $this->ipsclass->input['preview'] );
	$text = $this->core->api->display_parse( $text );

	$text = str_replace( '<#EMO_DIR#>', $this->ipsclass->skin['_emodir'], $text);

	print $text;
    die();
  }
  
  /**
  * This function check for the existance of a topic, makes the links accordingly.
  */
  function topic_manager($article)
	{
		// Whee!
		if( $article['article_tid'] != '0' )
		{
			// We have a topic, load it:
			$this->ipsclass->DB->simple_construct( array('select' => 'title' , 'from' => 'topics' , 'where' => 'tid = ' . $article['article_tid']) );
			$this->ipsclass->DB->simple_exec();
			
			if( $this->ipsclass->DB->get_num_rows() == 0 )
			{
				$this->ipsclass->DB->do_update( 'ams_articles' , array( 'article_tid' => '0' ) , 'article_id = ' . $article['article_id'] );
				$topic_link = $this->ipsclass->lang['ams_topic_noexist'].' <a id=\'ineo-topic-create\' href=\'{ipb.script_url}autocom=ineo&mod=xml&op=forward_to_create_topic\'>'.$this->ipsclass->lang['ams_topic_create'].'</a>?';
				$article['article_tid'] = '0';
			}
			else
			{
			$topic = $this->ipsclass->DB->fetch_row();
			
			$topic_link = "<b>".$this->ipsclass->lang['ams_discuss_on']."</b> <a id='ineo-topic-view' href='{$this->ipsclass->base_url}showtopic=".$article['article_tid']."'>{$topic['title']}</a>";
			}
			
			return $topic_link;
		}
		
	}
  
  /**
  * This function loads the editors, populates 'em, does all kinds of happy junk
  */
	function edit()
	{
    	$article = $this->lib_art->load_edit_data( $this->ipsclass->input['id'] );
    
    	$this->core->nav_add( $article['article_title'] , 'showarticle=' . $article['article_id'] );
    	$this->core->nav_add( $this->ipsclass->lang['ams_art_edit'] , 'mod=article&op=edit&id=' . $article['article_id'] );
    
    	$content = $this->core->api->editor_parse( $article['content_content'] );

    //-----------------------------------------
		// Load and config the std/rte editors
		//-----------------------------------------
		
		$editor_data = array( 'content' => $content,
		                      'id' => $this->ipsclass->input['id'],
		                      'title' => $article['article_title'] );

    	$editor = $this->core->api->edit_editor( $editor_data );
    	$cats   = $this->lib_global->category_dropdown($article['article_cat_id']);
		
		// Hand everything to the template. Hooray!
		$this->core->out .= $this->core->templates['global']->form_edit($editor,$article,$cats);
	}
	
	/**
	* This is pretty obvious... however...
	* Pull the article ids of non-queued articles, then pick one at random, and boink to it!
	*/
	function random()
	{
		$array = array( 
						'select' => 'article_id',
						'from' => 'ams_articles',
						'where' => 'article_is_queued = \'0\'',
						);
		
		$this->ipsclass->DB->simple_construct( $array );
		$this->ipsclass->DB->simple_exec();
		
		while( $cat = $this->ipsclass->DB->fetch_row() )
		{
			$cats[] = $cat['article_id'];
		}
		
		$rand_max = count( $cats ) - 1;
		
		$rand = $cats[rand( 0 , $rand_max )];
		
		$this->ipsclass->boink_it( $this->core->base_url . 'showarticle=' . $rand );
	}
	
	/**
	* This will be der submittin' der edit
	* Since it's so closely tied to the application it'll be running with, edit submission
	* will reside mainly in the appropriate api file.
	*/
	function edit_sub()
	{
	  if ( isset( $this->ipsclass->input['guestname'] ) )
	  {
	    $data['guestname'] = $this->ipsclass->input['guestname'];
	  }
	  
		$data['id']               = $this->ipsclass->input['id'];
		$data['article_content']  = $_POST['article_content']; // MUST USE RAW POST, ELSE WILL BORK AND EFF ITSELF
		$data['title']            = $this->ipsclass->input['title'];
		$data['description']      = $this->ipsclass->input['description'];
		$data['category']         = $this->ipsclass->input['category'];
		$data['article_links']    = $this->ipsclass->input['article_links'];
	  
		$this->lib_art->full_edit( $data );
    
    	// Check to see if the category changed during edit.
    	// If so, alert members who have the new category on their watchlist.
    	if ( $_POST['cat_check'] != $data['category'] )
    	{
      		$this->lib_global->watchlist_alert( $data['category'], 2, $data['id'] );
    	}
    
    	if ( $this->lib_art->edit_is_queued )
    	{
      		$this->ipsclass->boink_it( $this->core->base_url . 'showarticle=' . $data['id'] . '&msg=ams_rev_queued' );
    	}
    	else
    	{
      		$this->lib_global->watchlist_alert( $data['id'], 1 );
      		$this->ipsclass->boink_it( $this->core->base_url . 'showarticle=' . $data['id'] );
    	}
	}
	
	/**
	* Delete Article and Bounce to the index.
	*/
	function delete()
	{
		$id = $this->ipsclass->input['id'];
		$this->lib_art->delete_article( intval($id) );	
		$this->ipsclass->boink_it( $this->core->base_url . 'msg=ams_deleted' );
	}
	
	/**
	* @todo Make it not fugly, and borked.
	*/
	function printable()
	{
	  //----
	  // Create a simple, printable version of an article
	  //----
	  
    $this->ipsclass->DB->simple_construct( array( 'select' => 'a.*, c.*, m.members_display_name, e.members_display_name as last_edited_by',
                                                  'from' => array( 'ams_articles' => 'a'),
                                                  'add_join' => array( 1 =>
                                                                array( 'type' => 'left',
                                                                       'from' => array( 'ams_content' => 'c'),
                                                                       'where' => 'c.content_id=a.article_content'
                                                                     ),
                                                                       2 =>
                                                                array( 'type' => 'left',
                                                                       'from' => array( 'members' => 'm' ),
                                                                       'where' => 'm.id=a.article_author'
                                                                     ),
                                                                       3 =>
                                                                array( 'type' => 'left',
                                                                       'from' => array( 'members' => 'e' ),
                                                                       'where' => 'e.id=a.article_edited_by'
                                                                     )
                                                                     ),                                                                 
                                                  'where' => 'a.article_id = ' . $this->ipsclass->input['id']
                                                  ) );
	  $article = $this->ipsclass->DB->simple_exec();
	  $article = $this->ipsclass->DB->fetch_row( $article );
	  
	  $html = '';
	  
	  // Header
	  $html .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>'.$article['article_title'].'</title>
    <style type="text/css">
      body{
    	  margin:0;
    	  padding:5px;
    	  background:#fff;
    	  color:#000;
    	  font-family:Verdana, Arial, Helvetica, sans-serif;
    	  font-size:12px;
      }

      #print_titlewrap{
    	  margin:10px 0;
    	  padding:5px;
    	  border:1px solid #555;
    	  background:#eee;
    	  color:#000;
      }

      .print_title{
    	  font-weight:bold;
    	  font-size:15px;
      }

      .print_desc{
    	  font-size:12px;
    	  font-style:italic;
      }

      .quotetop,
      .codetop{
    	  margin:10px 0 0 0;
    	  padding:3px;
    	  border:1px dotted #555;
    	  border-bottom:0;
    	  background:#eee;
    	  color:#000;
      }

      .quotemain,
      .codemain{
    	  margin:0 0 10px 0;
    	  padding:3px;
    	  border:1px dotted #555;
    	  background:#fff;
    	  color:#000;
      }

      .codemain{
    	font-family:"Courier New", Courier, monospace;
        font-size:12px;
      }
    </style>
    </head>';
	  // Body of ze printable page
	  $html .= '<body><div id="print_titlewrap">';
	  $html .= '<span class="print_title">' . $article['article_title'] . '</span><br />';
	  $html .= '<span class="print_desc">' . $article['article_description'] . '</span></div>';
	  $html .= $article['content_content'];
	  
	  echo $html;
	  die();
	}
	
	function new_art()
	{
		$cats = $this->lib_art->build_catlist();
		
		$key = md5(uniqid(mt_rand(0, 100000)));
		
		//-----------------------------------------
		// Load and config the std/rte editors
		//-----------------------------------------
		require_once( ROOT_PATH."sources/handlers/han_editor.php" );
		$han_editor = new han_editor();
		$han_editor->ipsclass =& $this->ipsclass;
		$han_editor->remove_side_panel = 1;
		$han_editor->init();
		$editor_html = $han_editor->show_editor( '' , 'article_content' );
		
		$url = $this->core->base_url . 'mod=article&op=add';
		$box_title = $this->ipsclass->lang['ams_post_new'];
		$button_text = $this->ipsclass->lang['ams_art_post'];
		
		$this->core->out .= $this->core->templates['global']->form_newart($editor_html,$url,$button_text,$box_title,$cats,$key);
	}
	
	function add()
	{
	  $author = ( isset( $this->ipsclass->input['guestname'] ) ) ? $this->ipsclass->input['guestname'] : $this->ipsclass->member['id'];
		$title   = $this->ipsclass->input['title'];
		$desc    = $this->ipsclass->input['description'];
		$category = intval( $this->ipsclass->input['category'] );
		
    if ( empty($this->ipsclass->input['title']) )
	  {
	    $this->core->error( 'ams_notopic_error' );
	    return;
	  }
		
		$desc  = strip_tags( $desc );
		$title = strip_tags( $title );
		$links = str_replace( "<br />", "\n", $this->ipsclass->input['article_links']);
		
		require_once( ROOT_PATH."sources/handlers/han_editor.php" );
		$han_editor = new han_editor();
		$han_editor->ipsclass =& $this->ipsclass;
		$han_editor->init();
		
		require_once( $this->ipsclass->vars['base_path'] . 'sources/handlers/han_parse_bbcode.php' ); 
   		
   	$parse = new parse_bbcode();
   		
    $parse->ipsclass            =& $this->ipsclass;
    $parse->allow_update_caches = 1;		$parse->bypass_badwords     = intval($this->ipsclass->member['g_bypass_badwords']);
		$parse->parse_smilies       = 1;		$parse->parse_bbcode        = 1;		

		if( $han_editor->method == 'rte' )
		{
			$_POST['article_content'] = $parse->convert_ipb_html_to_html( $_POST['article_content'] );
		}
    
    $queued = ( $this->ipsclass->member['g_ams_queue'] == '0' && $this->ipsclass->vars['ams_queue_new'] == '1' ) ? '1' : '0';
    $insert = array(
    					'article_title' => $title,
    					'article_description' => $desc,
    					'article_cat_id' => $category,
    					'article_content' => 0,
    					'article_author' => $author,
    					'article_created_date' => time(),
    					'article_edited_date' => time(),
    					'article_is_queued' => $queued,
    					'article_links' => $links
    					);
		
   	$this->ipsclass->DB->do_insert( 'ams_articles' , $insert );
    	
		// Get insert ID for the article:
		$art_id = $this->ipsclass->DB->get_insert_id();
		
		$insert2 = array(
						'content_article' => $art_id,
						'content_author'  => $author,
						'content_date'    => time(),
						);
						
		// Fully formatted and ready to insert
		$insert2['content_content'] = $parse->pre_db_parse( $han_editor->process_raw_post( 'article_content' ) );    					
						
						
		$this->ipsclass->DB->do_insert( 'ams_content' , $insert2 );
    	
		// Get insert ID for the article:
		$cont_id = $this->ipsclass->DB->get_insert_id();
		
		$this->set_article_content( $art_id , $cont_id );
		
		// Alert members who have the assigned category on their watchlist.
		$this->lib_global->watchlist_alert( $category, 2, $art_id );
		
		// Make attachments be associated with the proper article.
		$this->ipsclass->DB->do_update('ams_attachments', array('attach_article' => $art_id), 'attach_article = \''.$this->ipsclass->input['key'].'\'');
		
		// Check to see if article has been queued. If so, redirect to ineo index w/system message.
		$this->ipsclass->DB->simple_construct( array( 'select' => 'article_is_queued', 'from' => 'ams_articles', 'where' => 'article_id = '.$art_id ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		
		if ( $data['article_is_queued'] == 1 )
		{
		  $this->ipsclass->boink_it( $this->core->base_url . 'msg=ams_new_queued' );
		}
		else
		{
      $this->ipsclass->boink_it( $this->core->base_url . 'showarticle=' . $art_id );
		}
	}
	
	function set_article_content( $article_id , $content_id )
	{
		$this->ipsclass->DB->do_update( 'ams_articles' , array( 'article_content' => $content_id ) , 'article_id = \'' . $article_id . '\'' );
	}
	
	function diff()
	{
    require_once( KERNEL_PATH.'class_difference.php' );
    $this->ipsclass->difference = new class_difference();
    $this->ipsclass->difference->ipsclass =& $this->ipsclass;
    
	  $this->ipsclass->DB->simple_construct( array( 'select' => 'content_content, content_article',
	                                                'from' => 'ams_content',
	                                                'where' => 'content_id = ' . $this->ipsclass->input['id'] ) );
    $this->ipsclass->DB->simple_limit( 1 );
	  $check = $this->ipsclass->DB->simple_exec();
	  $content = $this->ipsclass->DB->fetch_row($check);
	  
	  $this->ipsclass->DB->simple_construct( array( 'select' => 'a.article_content, a.article_title, a.article_id, c.content_content',
	                                                'from' => array( 'ams_articles' => 'a' ),
	                                                'add_join' => array( 1 => array(
	                                                              'type' => 'left',
	                                                              'from' => array( 'ams_content' => 'c' ),
	                                                              'where' => 'c.content_id = a.article_content' ) ),
	                                                'where' => 'a.article_id = ' . $content['content_article'] ) );
    $this->ipsclass->DB->simple_limit( 1 );
	  $check = $this->ipsclass->DB->simple_exec();
	  $article = $this->ipsclass->DB->fetch_row($check);
	  
	  $html = $this->ipsclass->difference->get_differences( $content['content_content'] , $article['content_content'] );
	  $html = html_entity_decode($html);
	  
	  /**
	  * @todo Please please please add language bits!
	  */
	  $this->core->nav_add( $article['article_title'], 'showarticle=' . $article['article_id'] );
	  $this->core->nav_add( 'Diff Report', 'mod=article&op=diff&id=' . $this->ipsclass->input['id'] );
	  
    $this->core->out .= $this->core->templates['articles']->diff_report($html);
	}
	
	function attach_add()
	{
	  if ( $this->ipsclass->member['g_ams_upload'] == '0' )
	  {
	    print $this->ipsclass->lang['ams_upload_no_perm'];
	    die();
	  }
	  
	  if ( ! $this->ipsclass->input['article_id'] )
	  {
	    die();
	  }
	  
    $ftypes = explode( ",", $this->ipsclass->vars['ams_upload_ftypes'] );
    require_once( KERNEL_PATH.'class_upload.php' );
    $this->ipsclass->upload = new class_upload();
    $this->ipsclass->upload->ipsclass =& $this->ipsclass;
    $this->ipsclass->upload->out_file_dir = $this->ipsclass->vars['ams_upload_path'];
    $this->ipsclass->upload->max_file_size = $this->ipsclass->vars['ams_upload_max'] * 1000;
    $this->ipsclass->upload->make_script_safe = 1;
    $this->ipsclass->upload->allowed_file_ext = $ftypes;
    $this->ipsclass->upload->upload_form_field = 'article_file';
    $this->ipsclass->upload->out_file_name = 'ams-'.time();
    $this->ipsclass->upload->force_data_ext = 'ams';
    $this->ipsclass->upload->upload_process();
    
   if ( $this->ipsclass->upload->error_no )
   {
	    switch( $this->ipsclass->upload->error_no )
	    {
		    case 1:
  			  // No upload
	  		  print $this->ipsclass->lang['ams_upload_no_file'];
				break;
		    case 2:
		    case 5:
  			  // Invalid file ext
	  		   print $this->ipsclass->lang['ams_upload_invalid_ext'];
				break;
		    case 3:
			    // Too big...
			     print $this->ipsclass->lang['ams_upload_filesize'];
					break;
        	case 4:
			    // Cannot move uploaded file
			     print $this->ipsclass->lang['ams_upload_failed'];
				break;
	    }
	
		die;
    }
    
    $insert = array( 'attach_file' => $this->ipsclass->upload->original_file_name,
                     'attach_location' => $this->ipsclass->upload->saved_upload_name,
                     'attach_ext' => $this->ipsclass->upload->real_file_extension,
                     'attach_article' => $this->ipsclass->input['article_id'],
                     'attach_isimage' => $this->ipsclass->upload->is_image,
                     'attach_size' => $_FILES['article_file']['size'],
                     'attach_mid' => $this->ipsclass->member['id'] );
    
    	$this->ipsclass->DB->do_insert( 'ams_attachments', $insert );

    	print '<html><body onLoad="javascript:window.parent.postUploadAttach(\''.$this->ipsclass->input['article_id'].'\')">';
    	
		$html = $this->core->templates['articles']->attach_frame( $this->ipsclass->input['article_id'] , $this->ipsclass->upload->original_file_name );
    	
		die( $html );
	}
	
	function attach_download()
	{
	  if ( $this->ipsclass->member['g_ams_view'] == '0' )
	  {
	    print $this->ipsclass->lang['ams_upload_no_download'];
	    die();
	  }
	  $this->ipsclass->DB->simple_construct( array( 'select' => 'a.*, m.*',
	                                                'from' => array( 'ams_attachments' => 'a' ),
	                                                'add_join' => array( 1 => 
	                                                              array( 'type' => 'left',
	                                                                     'from' => array( 'attachments_type' => 'm' ),
	                                                                     'where' => 'm.atype_extension = a.attach_ext' )),
	                                                'where' => 'a.attach_id = '.$this->ipsclass->input['id'] ) );
	  $this->ipsclass->DB->simple_exec();
	  $file = $this->ipsclass->DB->fetch_row();

	  header( 'Content-type: '.$file['atype_mimetype'] );
	  
	  if ( strpos( $file['atype_mimetype'], 'image' ) === false )
	  {
	    header( 'Content-Disposition: attachment; filename="'.$file['attach_file'].'"' );
	  }
	  else
	  {
	    header( 'Content-Disposition: inline; filename="'.$file['attach_file'].'"' );
	  }
	  
	  print file_get_contents( $file['attach_location'] );
	  
	  die();
	}
	
	function attach_frame()
	{
	  if ( $this->ipsclass->member['g_ams_upload'] == '0' )
	  {
	    echo $this->ipsclass->lang['ams_upload_no_perm'];
	    die();
	  }
	  
	  if ( ! $this->ipsclass->input['id'] )
	  {
	    die();
	  }
	  
    $html = $this->core->templates['articles']->attach_frame(intval($this->ipsclass->input['id']));
    print $html;
    die();
	}
	
	function new_attach_frame()
	{
	  if ( $this->ipsclass->member['g_ams_upload'] == '0' )
	  {
	    print $this->ipsclass->lang['ams_upload_no_perm'];
	    die();
	  }
	  
	  if ( ! $this->ipsclass->input['key'] )
	  {
	    print $this->ipsclass->lang['ams_upload_no_key'];
	    die();
	  }
	  
    	$html = $this->core->templates['articles']->attach_frame($this->ipsclass->input['key']);
    	print $html;
    	die();
	}
	
}

?>